package controller.notifcations;

import android.content.Context;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;

import com.trek2000.android.enterprise.Enterprise;
import com.trek2000.android.enterprise.R;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import controller.group_management.GroupManagementAsync;
import define.API;
import define.Key;
import listener.notifications.CompanyNotificationsScrollListener;
import ui.fragment.group_management.GroupManagementFragment;
import utils.Utils;

/**
 * Created by trek2000 on 19/8/2014.
 */
public class AcceptInvitationToCompanyGroupAsync extends AsyncTask<String, Void, Boolean> {

    /**
     * String section
     */
    private String STATUS = "";

    /**
     * The others section
     */
    private Context mContext;

    public AcceptInvitationToCompanyGroupAsync(Context context) {
        this.mContext = context;
    }

    @Override
    protected Boolean doInBackground(String... params) {
        return getData(params);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);

        // hide waiting dialog
        Utils.hideWaitingDialog();

        if (!result) {
            Toast.makeText(mContext, STATUS ,
                    Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(mContext.getApplicationContext(), STATUS ,
                    Toast.LENGTH_SHORT).show();
            //clear old data of select company
            if (GroupManagementAsync.mAlGroupId != null &&
                    !GroupManagementAsync.mAlGroupId.isEmpty())
                GroupManagementAsync.mAlGroupId.clear();
            if (GroupManagementAsync.mAlGroupManagement != null &&
                    !GroupManagementAsync.mAlGroupManagement.isEmpty())
                GroupManagementAsync.mAlGroupManagement.clear();
            if (GroupManagementFragment.groupManagementAdapter != null)
                GroupManagementFragment.groupManagementAdapter.notifyDataSetChanged();
            //use context of enterprise activity to transfer fragment
            // go to group management
            ((FragmentActivity) Enterprise.mContext).getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fl_in_activity_enterprise, GroupManagementFragment.newInstance())
                    .commitAllowingStateLoss();
            //set again title for action bar
            Enterprise.mTvTitle.setText(mContext.getString(R.string.group_management));
            //clear old notifications
            if (!CompanyNotificationsAsync.mAlId.isEmpty())
                CompanyNotificationsAsync.mAlId.clear();
            if (!CompanyNotificationsAsync.mAlCompanyNotifications.isEmpty())
                CompanyNotificationsAsync.mAlCompanyNotifications.clear();
            //clear on scroll listener
            CompanyNotificationsScrollListener.visibleThreshold = 0;
            CompanyNotificationsScrollListener.currentPage = 0;
            CompanyNotificationsScrollListener.previousTotal = 0;
            CompanyNotificationsScrollListener.loading = true;
        }
    }

    /**
     * Basic methods
     */
    private boolean getData(String[] params) {
        HttpPost mHttpPost = new HttpPost(API.ACCEPT_INVITATION_TO_COMPANY_GROUP);
        List<NameValuePair> mListValues = new ArrayList<>();
        /**
         * user_global_id
         * user_emails
         * company_id
         */
        mListValues.add(new BasicNameValuePair(Key.USER_GLOBAL_ID, params[0]));
        mListValues.add(new BasicNameValuePair(Key.USER_EMAIL, params[1]));
        mListValues.add(new BasicNameValuePair(Key.COMPANY_ID, params[2]));
        mListValues.add(new BasicNameValuePair(Key.GROUP_ID, params[3]));

        try {
            mHttpPost.setEntity(new UrlEncodedFormEntity(mListValues));
            HttpParams mHttpParams = new BasicHttpParams();

            int TIMEOUT_CONNECTION = 30000;
            int TIMEOUT_SOCKET = 30000;

            HttpConnectionParams.setConnectionTimeout(
                    mHttpParams, TIMEOUT_CONNECTION);
            HttpConnectionParams.setSoTimeout(mHttpParams, TIMEOUT_SOCKET);
            HttpClient mHttpclient = new DefaultHttpClient(mHttpParams);
            HttpResponse mHttpResponse;
            mHttpResponse = mHttpclient.execute(mHttpPost);
            HttpEntity mHttpEntity = mHttpResponse.getEntity();
            String XML = EntityUtils.toString(mHttpEntity);

            Log.i("", AcceptInvitationToCompanyGroupAsync.class.getSimpleName() + " " + XML);

            JSONObject mJoXml = new JSONObject(XML);
            //get string in mJoXml
            STATUS = mJoXml.getString(Key.STATUS);
            if (STATUS.equals(mContext.getString(R.string.success_)))
                return  true;
        } catch (ClassCastException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ConnectTimeoutException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}